<template>
  <div class="app-container user-form-container">
    <div class="page-title">电动车信息录入</div>
    <van-form v-show="formId==1" class="edit-form" error-message-align="right">
      <van-field
        v-model="form.mobile"
        label="手机号"
        type="tel"
        name="mobile"
        placeholder="请输入手机号"
        maxlength="11"
        input-align="right"
        :rules="mobileRules"
        required
      />
      <div class="form-footer">
        <van-button round type="info" size="normal" @click="checkMobile"> 下一步 </van-button>
      </div>
    </van-form>

    <van-form v-show="formId==2" class="edit-form" error-message-align="right" @submit="submitForm">
      <van-cell-group title="车主基本信息" inset class="info-cell-group user-group">
        <van-field
          v-model="form.name"
          label="车主姓名"
          name="name"
          placeholder="请输入车主姓名"
          input-align="right"
          maxlength="10"
          :rules="[{ required: true }]"
          required
        />
        <!--        <van-field label="手机号" type="tel" v-model="form.mobile" name="mobile" placeholder="请输入车主手机号" maxlength="11"-->
        <!--                   input-align="right" :rules="[{ required: true }]" required-->
        <!--        />-->
      </van-cell-group>

      <van-cell-group title="现住址" inset class="info-cell-group user-group">
        <!--        <van-field label="现住址" v-model="addrText" name="addr" placeholder="请选择现住址" @click="onClickAddr" :rules="[{ required: true }]" required is-link readonly/>-->
        <!--        <van-field label="社区" v-model="form.community_id" name="community_id" placeholder="请选择社区" :rules="[{ required: true }]" required/>-->
        <van-field
          label="村/社区"
          :value="communityText"
          placeholder="请选择村/社区"
          :rules="[{ required: true }]"
          is-link
          readonly
          required
          @click="showCommunityPopup=true"
        />
        <van-field
          label="门牌号"
          :value="houseText"
          placeholder="请选择门牌号"
          :rules="[{ required: true }]"
          is-link
          readonly
          required
          @click="showHousePopup=true"
        />
        <van-field
          v-model="form.addr"
          label="单元/房间号"
          name="house_other"
          placeholder="请填写单元、房间号"
          :rules="[{ required: true }]"
          maxlength="40"
          required
        />
      </van-cell-group>

      <van-cell-group title="车辆信息" inset class="info-cell-group vehicle-group">
        <van-field
          label="车辆状况"
          :value="vehicleStateText"
          name="vehicle_state"
          placeholder="请选择车辆状况"
          :rules="[{ required: true }]"
          required
          is-link
          readonly
          @click="showVehicleStatePopup=true"
        />
        <van-field
          v-show="form.vehicle_state!=3"
          v-model="form.vehicle_plate_no"
          label="车牌号码"
          name="plate_no"
          placeholder="请输入车牌号码"
          input-align="right"
          :rules="platNoRules"
          maxlength="10"
          required
        />
        <van-field
          label="车辆类型"
          :value="vehicleTypeText"
          placeholder="请选择车辆类型"
          :rules="[{ required: true }]"
          required
          is-link
          readonly
          @click="showVehicleTypePopup=true"
        />
        <van-field
          label="车辆用途"
          :value="vehicleUseToText"
          placeholder="请选择车辆用途"
          :rules="[{ required: true }]"
          required
          is-link
          readonly
          @click="showVehicleUseToPopup=true"
        />
      </van-cell-group>

      <van-cell-group title="电池信息" inset class="info-cell-group battery-group">
        <van-field
          label="电池类型"
          :value="batteryTypeText"
          placeholder="请选择电池类型"
          :rules="[{ required: true }]"
          required
          is-link
          readonly
          @click="showBatteryTypePopup=true"
        />
        <van-field
          label="电池情况"
          :value="batteryStateText"
          placeholder="请选择电池情况"
          :rules="[{ required: true }]"
          required
          is-link
          readonly
          @click="showBatteryStatePopup=true"
        />
        <van-field
          label="电池外观"
          :value="batteryAppearanceText"
          placeholder="请选择电池外观"
          :rules="[{ required: true }]"
          required
          is-link
          readonly
          @click="showBatteryAppearancePopup=true"
        />
        <van-field
          label="购买日期"
          :value="produceDateText"
          placeholder="请选择购买日期"
          :rules="[{ required: true }]"
          required
          is-link
          readonly
          @click="showProduceDatePopup=true"
        />

        <van-cell title="是否三无(无标识信息)" required>
          <template>
            <van-radio-group v-model="form.battery_no_id" class="is-no-id">
              <van-radio :name="1">是</van-radio>
              <van-radio :name="0">否</van-radio>
            </van-radio-group>
          </template>
        </van-cell>

      </van-cell-group>

      <div class="form-footer">
        <van-button round type="info" size="normal" native-type="submit"> 提交</van-button>
      </div>
      <div v-show="redirect" class="form-footer-bottom-tip" @click="gotoNext()"> 稍后再提交</div>
    </van-form>

    <van-popup v-model="showCommunityPopup" position="bottom" round closeable>
      <div class="popup-title">
        <span>选择社区</span>
      </div>
      <div class="popup-body">
        <van-radio-group v-model="form.community_id">
          <van-cell
            v-for="community in communityList"
            :key="'community'+community.id"
            :title="community.name"
            clickable
            @click="chooseCommunity(community.id,community.name)"
          >
            <template #right-icon>
              <van-radio :name="community.id" />
            </template>
          </van-cell>
        </van-radio-group>
      </div>
    </van-popup>

    <van-popup v-model="showHousePopup" position="bottom" style="max-height: 95%" round closeable>
      <div class="popup-title">
        <span>选择门牌号</span>
      </div>
      <div class="popup-body">
        <van-radio-group v-model="form.house_id">
          <van-cell
            v-for="house in curHouseList"
            :key="'house'+house.id"
            :title="house.name"
            clickable
            @click="chooseHouse(house.id,house.name)"
          >
            <template #right-icon>
              <van-radio :name="house.id" />
            </template>
          </van-cell>
        </van-radio-group>
      </div>
    </van-popup>

    <van-dialog v-model="showHouseInputDialog" title="填写门牌号" :before-close="beforeCloseHouseInputDialog" show-cancel-button @confirm="confirmInputHouseName">
      <div class="house-input-dialog">
        <van-form>
          <van-field v-model="input_house_name" label="门牌号" placeholder="请准确填写门牌号" required maxlength="20" />
          <div v-show="showHouseInputError" class="error-input-tip">{{ houseInputError }}</div>
        </van-form>
      </div>
    </van-dialog>

    <van-popup v-model="showVehicleStatePopup" position="bottom" round closeable>
      <div class="popup-title">
        <span>选择车辆状况</span>
      </div>
      <div class="popup-body">
        <van-radio-group v-model="form.vehicle_state">
          <van-cell key="vehicle_state1" title="普通车" clickable @click="chooseVehicleState(1,'普通车')">
            <template #right-icon>
              <van-radio :name="1" />
            </template>
          </van-cell>
          <van-cell key="vehicle_state2" title="黄牌车" clickable @click="chooseVehicleState(2,'黄牌车')">
            <template #right-icon>
              <van-radio :name="2" />
            </template>
          </van-cell>
          <van-cell key="vehicle_state3" title="无牌车" clickable @click="chooseVehicleState(3,'无牌车')">
            <template #right-icon>
              <van-radio :name="3" />
            </template>
          </van-cell>
          <van-cell key="vehicle_state4" title="改装车" clickable @click="chooseVehicleState(4,'改装车')">
            <template #right-icon>
              <van-radio :name="4" />
            </template>
          </van-cell>
        </van-radio-group>
      </div>
    </van-popup>

    <van-popup v-model="showVehicleTypePopup" position="bottom" round closeable>
      <div class="popup-title">
        <span>请选择车辆类型</span>
      </div>
      <div class="popup-body">
        <van-radio-group v-model="form.vehicle_type">
          <van-cell key="vehicle_type1" title="两轮车" clickable @click="chooseVehicleType(1,'两轮车')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="1" />
            </template>
          </van-cell>
          <van-cell key="vehicle_type2" title="三轮车" clickable @click="chooseVehicleType(2,'三轮车')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="2" />
            </template>
          </van-cell>
        </van-radio-group>
      </div>
    </van-popup>

    <van-popup v-model="showVehicleUseToPopup" position="bottom" round closeable>
      <div class="popup-title">
        <span>请选择车辆用途</span>
      </div>
      <div class="popup-body">
        <van-radio-group v-model="form.vehicle_use_to">
          <van-cell key="vehicle_useto1" title="自用" clickable @click="chooseVehicleUseTo(1,'自用')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="1" />
            </template>
          </van-cell>
          <van-cell key="vehicle_useto2" title="外卖" clickable @click="chooseVehicleUseTo(2,'外卖')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="2" />
            </template>
          </van-cell>
          <van-cell key="vehicle_useto3" title="快递" clickable @click="chooseVehicleUseTo(3,'快递')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="3" />
            </template>
          </van-cell>
          <van-cell key="vehicle_useto99" title="其他" clickable @click="chooseVehicleUseTo(99,'其他')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="99" />
            </template>
          </van-cell>
        </van-radio-group>
      </div>
    </van-popup>

    <van-popup v-model="showBatteryTypePopup" position="bottom" round closeable>
      <div class="popup-title">
        <span>选择电池类型</span>
      </div>
      <div class="popup-body">
        <van-radio-group v-model="form.battery_type">
          <van-cell key="battery_state1" title="锂电池" clickable @click="chooseBatteryType(1,'锂电池')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="1" />
            </template>
          </van-cell>
          <van-cell key="battery_state2" title="铅酸电池" clickable @click="chooseBatteryType(2,'铅酸电池')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="2" />
            </template>
          </van-cell>
        </van-radio-group>
      </div>
    </van-popup>

    <van-popup v-model="showBatteryStatePopup" position="bottom" round closeable>
      <div class="popup-title">
        <span>选择电池状况</span>
      </div>
      <div class="popup-body">
        <van-radio-group v-model="form.battery_state">
          <van-cell key="battery_state1" title="原装" clickable @click="chooseBatteryState(1,'原装')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="1" />
            </template>
          </van-cell>
          <van-cell key="battery_state2" title="改装" clickable @click="chooseBatteryState(2,'改装')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="2" />
            </template>
          </van-cell>
          <van-cell key="battery_state3" title="超大容量" clickable @click="chooseBatteryState(3,'超大容量')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="3" />
            </template>
          </van-cell>
        </van-radio-group>
      </div>
    </van-popup>

    <van-popup v-model="showBatteryAppearancePopup" position="bottom" round closeable>
      <div class="popup-title">
        <span>选择电池外观</span>
      </div>
      <div class="popup-body">
        <van-radio-group v-model="form.battery_appearance">
          <van-cell key="battery_appearance1" title="正常" clickable @click="chooseBatteryAppearance(1,'正常')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="1" />
            </template>
          </van-cell>
          <van-cell key="battery_appearance2" title="破损" clickable @click="chooseBatteryAppearance(2,'破损')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="2" />
            </template>
          </van-cell>
          <van-cell key="battery_appearance3" title="变形" clickable @click="chooseBatteryAppearance(3,'变形')">
            <template #right-icon>
              <van-radio ref="radioBox" :name="3" />
            </template>
          </van-cell>
        </van-radio-group>
      </div>
    </van-popup>

    <van-popup v-model="showProduceDatePopup" position="bottom" round>
      <div class="popup-body">
        <van-datetime-picker
          v-model="produceDate"
          type="year-month"
          title="选择购买日期"
          :min-date="produceMinDate"
          :max-date="produceMaxDate"
          :formatter="formatter"
          @cancel="cancelProduceDate"
          @confirm="confirmProduceDate"
        />
      </div>
    </van-popup>

    <van-popup v-model="showAddrPopup" round position="bottom">
      <van-picker
        ref="addrPicker"
        title="选择现住址"
        :value="addrText"
        :columns="communityList"
        show-toolbar
        @change="onChangeAddr"
        @confirm="confirmAddr"
        @cancel="cancelAddr"
      />
    </van-popup>

  </div>
</template>

<script>
import infoApi from '@/api/info'
import addrApi from '@/api/addr'
import { formatDateTime } from '@/utils/common'

export default {
  name: 'Auth',
  components: {},
  dicts: [],

  data() {
    return {
      formId: 1,
      form: {},
      redirect: '',
      communityId: 0,

      input_house_name: '',

      showCommunityPopup: false,
      showHousePopup: false,
      showHouseInputDialog: false,
      showHouseInputError: false,
      houseInputError: '',
      showAddrPopup: false,

      showVehicleTypePopup: false,
      showVehicleUseToPopup: false,
      showVehicleStatePopup: false,

      showBatteryTypePopup: false,
      showBatteryStatePopup: false,
      showBatteryAppearancePopup: false,
      showProduceDatePopup: false,
      produceMinDate: new Date(2000, 0, 1),
      produceMaxDate: new Date(),
      produceDate: new Date(),

      communityText: '',
      houseText: '',
      addrText: '',

      vehicleTypeText: '',
      vehicleUseToText: '',
      vehicleStateText: '',

      batteryTypeText: '',
      batteryStateText: '',
      batteryAppearanceText: '',
      produceDateText: '',

      communityList: [],
      houseList: [],
      curHouseList: [],

      platNoRules: [
        {
          validator: value => {
            if (this.form.vehicle_state == 3) {
              return true
            }
            if (!value || value.length <= 0) {
              return false
            }
          },
          message: '',
          trigger: 'onBlur'
        }
      ],
      mobileRules: [
        {
          required: true,
          message: '',
          trigger: 'onBlur'
        },
        {
          validator: value => {
            if (value.trim().length !== 11) {
              return false
            }
            return true
          },
          message: '请输入正确的手机号码',
          trigger: 'onBlur'
        }
      ]
    }
  },

  created() {
    if (this.$route.query.redirect) {
      console.log('redirect : ', this.$route.query.redirect)
      this.redirect = decodeURIComponent(this.$route.query.redirect)
    }
    if (this.$route.query.community_id) {
      this.communityId = parseInt(this.$route.query.community_id)
      this.form.community_id = this.communityId
    }

    addrApi.getAllCommunity().then(res => {
      if (res && res.data && res.data.length > 0) {
        if (!this.communityId) {
          this.communityId = res.data[0].id
        }
        for (let i = 0; i < res.data.length; i++) {
          if (res.data[i].id == this.communityId) {
            this.form.community_id = this.communityId
            this.communityText = res.data[i].name
          }
        }
        this.communityList = res.data

        addrApi.getHouse({ 'community_id': this.communityId }).then(res => {
          if (res && res.data && res.data.length > 0) {
            const list = res.data
            list.push({ 'id': 0, 'name': '以上都不是，手动填写' })
            this.houseList[this.communityId] = list
            this.curHouseList = list
          }
        })
      }
    })
  },

  methods: {
    checkMobile: function() {
      console.log('checkMobile:')
      if (!this.form.mobile || this.form.mobile.trim().length !== 11) {
        return
      }

      infoApi.checkMobile(this.form).then(res => {
        console.log('checkMobile res:', res)
        if (res.code === 0 && res.data === 1) {
          this.gotoNext()
        } else {
          this.formId = 2
        }
      })
    },
    submitForm: function(valid) {
      console.log('submitForm  valid:', valid, ' form:', this.form)

      infoApi.saveInfo(this.form).then(res => {
        console.log('save info res:', res)
        if (res.code === 0) {
          this.$dialog.alert({
            message: '提交成功'
          }).then(() => {
            this.gotoNext()
          })
        } else {
          this.$dialog.alert({
            message: res.msg ? res.msg : '提交失败'
          })
        }
      }).catch(() => {
        this.$dialog.alert({
          message: '提交失败'
        }).then(() => {
          this.gotoNext()
        })
      })
    },

    chooseCommunity(id, name) {
      this.form.community_id = id
      this.communityText = name
      this.showCommunityPopup = false

      if (this.houseList[id]) {
        this.curHouseList = this.houseList[id]
      } else {
        addrApi.getHouse({ 'community_id': id }).then(res => {
          if (res && res.data && res.data.length > 0) {
            const list = res.data
            list.push({ 'id': 0, 'name': '以上都不是，手动填写' })

            this.houseList[id] = list
            this.curHouseList = list
          }
        })
      }
    },

    chooseHouse(id, name) {
      this.form.house_id = id
      this.houseText = name
      this.showHousePopup = false
      console.log('chooseHouse id:', id, ' name:', name)
      if (id === 0) {
        console.log('chooseHouse id===0:', id, ' name:', name)
        this.houseText = ''
        this.showHouseInputDialog = true
      }
    },

    beforeCloseHouseInputDialog(action, done) {
      console.log('beforeCloseHouseInputDialog： ', action, ' house_name:', this.input_house_name)
      if (action === 'confirm') {
        if (!this.input_house_name) {
          return done(false)
        } else {
          return done(true)
        }
      } else {
        return done(true)
      }
    },

    confirmInputHouseName() {
      console.log('confirmInputHouseName： ', this.input_house_name)
      if (!this.input_house_name) {
        console.log('confirmInputHouseName 2： ', this.input_house_name)
        this.showHouseInputError = true
        this.houseInputError = '请输入门牌号'
        return
      }

      console.log('confirmInputHouseName  3： ', this.input_house_name)

      this.showHouseInputError = false
      this.houseInputError = ''
      this.houseText = this.input_house_name
      this.form.house_name = this.input_house_name
      this.showHouseInputDialog = false
    },

    chooseVehicleState(vehicleState, vehicleStateText) {
      console.log('vehicleState：', vehicleState, ' vehicleStateText:', vehicleStateText)
      this.form.vehicle_state = vehicleState
      this.vehicleStateText = vehicleStateText
      this.showVehicleStatePopup = false
    },
    chooseVehicleType(vehicleType, vehicleTypeText) {
      this.form.vehicle_type = vehicleType
      this.vehicleTypeText = vehicleTypeText
      this.showVehicleTypePopup = false
    },
    chooseVehicleUseTo(useTo, useToText) {
      this.form.vehicle_use_to = useTo
      this.vehicleUseToText = useToText
      this.showVehicleUseToPopup = false
    },

    chooseBatteryAppearance(batteryAppearance, batteryAppearanceText) {
      this.form.battery_appearance = batteryAppearance
      this.batteryAppearanceText = batteryAppearanceText
      this.showBatteryAppearancePopup = false
    },
    chooseBatteryState(batteryState, batteryStateText) {
      this.form.battery_state = batteryState
      this.batteryStateText = batteryStateText
      this.showBatteryStatePopup = false
    },
    chooseBatteryType(batteryType, batteryTypeText) {
      this.form.battery_type = batteryType
      this.batteryTypeText = batteryTypeText
      this.showBatteryTypePopup = false
    },

    formatter(type, val) {
      if (type === 'month') {
        return `${val}月`
      } else if (type === 'day') {
        return `${val}日`
      }
      return val
    },

    cancelProduceDate() {
      this.showProduceDatePopup = false
    },
    confirmProduceDate(date) {
      const dateFormat = formatDateTime(date, '{y}-{m}')
      this.form.battery_produce_date = dateFormat
      this.produceDateText = dateFormat
      this.showProduceDatePopup = false
    },

    // onClickAddr() {
    //   this.showAddrPopup = true
    //   this.$nextTick(() => {
    //     for (let i = 0; i < this.communityList.length; i++) {
    //       if (this.communityList[i].id == this.communityId) {
    //         this.$refs.addrPicker.setColumnIndex(0, i)
    //       }
    //     }
    //   })
    // },

    onChangeAddr(picker, values) {
      console.log('onChangeAddr', picker, values)

      if (this.communityList) {
        for (let i = 0; i < this.communityList.length; i++) {
          if (values[0] == this.communityList[i].text && this.communityList[i].children && this.communityList[i].children.length <= 1) {
            addrApi.getHouse({ 'community_name': values[0] }).then(res => {
              if (res && res.data && res.data.length > 0) {
                const children = []
                for (let j = 0; j < res.data.length; j++) {
                  children.push({ 'id': res.data[i].id, 'text': res.data[i].name })
                }
                children.push({ 'text': '其他' })
                this.communityList[i].children = children
                picker.setColumnValues(1, children)
              }
            })
          }
        }
      }
    },

    confirmAddr(value) {
      console.log('confirmAddr:', value)
      this.form.community = value[0]
      this.form.house = value[1]
      this.addrText = value[0] + '/' + value[1]
      this.showAddrPopup = false
    },
    cancelAddr() {
      this.showAddrPopup = false
    },
    gotoNext() {
      if (this.redirect && this.redirect.indexOf('http') === 0) {
        window.location.href = this.redirect
      } else {
        this.$dialog.alert({
          message: '信息录入完成！'
        }).then(() => {

        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.user-form-container {
  background: #ededed57;
  min-height: 100%;

  .page-title {
    text-align: center;
    height: 30px;
    line-height: 30px;
    font-size: 18px;
    font-weight: 400;
  }

  .edit-form {
    margin-top: 10px;
    padding-bottom: 40px;

    ::v-deep.van-cell {
      .van-cell__title {
        flex: none;
        width: 130px;
      }

      .van-field__body {
        .van-field__control {
          text-align: right;
        }
      }
    }

    ::v-deep.van-cell--clickable {
      .van-icon-arrow.van-cell__right-icon {
        height: 30px;
        line-height: 30px;
      }
    }

    .van-cell-group--inset {
      margin: 0;
    }

    .van-cell-group {
      margin-bottom: 10px;
    }

    .van-radio-group.is-no-id {
      display: flex;
      gap: 25px;
      justify-content: flex-end;
    }

    .van-cell-group__title--inset {
      padding: 16px 16px 8px 16px;
    }

    ::v-deep .van-field .van-field__label {
      width: 9em;
    }

    .van-cell {
      line-height: 30px;

      .van-cell__title {
        color: #646566;
      }

      .cell-extra {
        margin-left: 10px;
        color: #646566;
      }
    }

    .form-footer {
      display: flex;
      justify-content: center;
      gap: 30px;
      margin-top: 40px;

      .van-button--normal {
        width: 200px;
      }
    }

    .form-footer-bottom-tip {
      margin-top: 20px;
      text-align: center;
      color: #5094d5;
    }
  }

  .van-popup {
    .popup-title {
      text-align: center;
      line-height: 65px;
      position: sticky;
      top: 0;
      left: 0;
      right: 0;
      z-index: 1;
      background: #fff;
      border-bottom: solid 1px #f5f5f7;

      .check-right {
        position: absolute;
        right: 26px;
        top: 0;
        height: 46px;
        line-height: 46px;
        display: flex;
        align-items: center;

        span {
          margin-right: 8px;
        }
      }
    }

    .popup-body {
      padding: 10px 10px 10px 10px;
    }

    .popup-footer {
      position: fixed;
      background: #fff;
      bottom: 0;
      left: 0;
      right: 0;
      display: flex;
      justify-content: center;
      gap: 30px;
      padding: 10px;
      border-top: solid 1px #f5f5f7;

      .van-button {
        width: 100px;
      }
    }
  }

  .house-input-dialog {
    padding: 30px 10px;
    .van-field__control{
      text-align: right;
    }
    .error-input-tip{
      height: 15px;
      line-height: 15px;
      text-align: right;
      margin: 10px 0 0 0;
      color: #ee0a0a;
      font-size: 14px;
    }
  }
}

</style>

